package com.sangeng.filter;

import com.alibaba.fastjson.JSON;
import com.sangeng.config.RedisCache;
import com.sangeng.entity.ResponseResult;
import com.sangeng.enums.AppHttpCodeEnum;
import com.sangeng.util.JwtUtil;
import com.sangeng.util.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
     @Autowired
    RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
//如果没有携带token就直接放行，比如第一次登录时肯定是没有token的
            filterChain.doFilter(request,response);
            //return 的目的是为了不执行下面的代码了
            return;
        }
        Claims claims=null;
        //解析token，获取放在token里面的信息，比如userId
        try {
             claims = JwtUtil.parseJWT(token);

        } catch (Exception e) {
            //当jwt被修改或者过期就会抛异常
            e.printStackTrace();
         //将错误信息返回给前端
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
           return;

        }
        String userId =claims.getSubject();
        //从redis中获取到user的信息,如果获取不到，说明过期了,登陆过期，重新登录
        Object loginUser = redisCache.getCacheObject("adminLogin:" + userId);
        if(Objects.isNull(loginUser)){
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response,JSON.toJSONString(result));
            return;
        }
        //如果获取到了，就存到


        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
